﻿using Newtonsoft.Json.Linq;
using System;
using Wicture.DbRESTFul.SQL;

namespace Wicture.EPC.Service.V1.Repository
{
    public class PreprocessRepository : DbRESTFulRepository, IParameterPreprocessor
    {
        [PreprocessMethod]
        public JToken GetModelForHonda(JToken param)
        {
            return GetModelForHonda(param, true);
        }

        [PreprocessMethod]
        public JToken TryGetModelForHonda(JToken param) // No exception throw if parameter invalid.
        {
            return GetModelForHonda(param, false);
        }

        private JToken GetModelForHonda(JToken param, bool throwExpcetionWhenFailed)
        {
            SqlConnectionManager.ProcessGateway(null, param, null);

            dynamic model = null;
            if (param["selectorId"] != null && !string.IsNullOrEmpty(param.Value<string>("selectorId")) && param.Value<int>("selectorId") > 0)
            {
                model = base.Invoke(CSIs.Get_Model_By_Selector_ID, param);
            }
            else if (!string.IsNullOrEmpty(param.Value<string>("vin")))
            {
                var vin = param.Value<string>("vin");
                if (vin.Length == 17)
                {
                    var prefix = $"{vin.Substring(0, 8)}*{vin.Substring(9, 2)}";
                    var sequence = vin.Substring(9);
                    model = base.Invoke(CSIs.Get_Model_By_Vin_For_Honda, new { prefix, sequence, brandCode = param.Value<string>("brandCode") });
                    if (model==null && throwExpcetionWhenFailed) throw new InvalidOperationException("VIN code is invalid.");
                }
            }

            if (model != null)
            {
                param["npl"] = model.npl;
                param["modelId"] = model.id;
            }
            else if (throwExpcetionWhenFailed)
            {
                throw new Exception($"Unable to find model with selectorId and vin.");
            }

            return param;
        }
    }
}
